package com.example.changtest

import android.app.Application
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import com.example.changtest.cockroach.Cockroach
import com.example.changtest.cockroach.ExceptionHandler
import com.example.changtest.cockroach.support.CrashLog
import com.example.changtest.cockroach.support.DebugSafeModeTipActivity
import com.example.changtest.cockroach.support.DebugSafeModeUI
import java.lang.RuntimeException
import com.example.changtest.util.CrashHandler
import java.lang.Exception


/**
 * @Description:
 * @author: zcs
 * @email: 1059737741@qq.com
 * create at 2022/1/22 15:20
 */
class App :Application() {

    override fun onCreate() {
        super.onCreate()

        //install()
        CrashHandler.instance.init(this)
    }

    private fun install() {
        val sysExcepHandler = Thread.getDefaultUncaughtExceptionHandler()
        val toast = Toast.makeText(this, "", Toast.LENGTH_SHORT)
        DebugSafeModeUI.init(this)
        Cockroach.install(this, object : ExceptionHandler() {
             override fun onUncaughtExceptionHappened(thread: Thread, throwable: Throwable?) {
                Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:$thread<---", throwable)
//                CrashLog.saveCrashLog(applicationContext, throwable)
                Handler(Looper.getMainLooper()).post {
//                    toast.setText(R.string.safe_mode_excep_tips)
//                    toast.show()
                }
            }

             override fun onBandageExceptionHappened(throwable: Throwable) {
                throwable.printStackTrace() //打印警告级别log，该throwable可能是最开始的bug导致的，无需关心
//                toast.setText("Cockroach Worked")
//                toast.show()
            }

             override fun onEnterSafeMode() {
//                val tips: Int = R.string.safe_mode_tips
//                Toast.makeText(this@App, resources.getString(tips), Toast.LENGTH_LONG).show()
      //          DebugSafeModeUI.showSafeModeUI()
//                if (BuildConfig.DEBUG) {
//                    val intent = Intent(this@App, DebugSafeModeTipActivity::class.java)
//                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
//                    startActivity(intent)
//                }
            }

             override fun onMayBeBlackScreen(e: Throwable?) {
                val thread = Looper.getMainLooper()?.thread
                Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:$thread<---", e)
                //黑屏时建议直接杀死app
                sysExcepHandler?.uncaughtException(thread, RuntimeException("black screen"))
            }
        })
    }



}